package com.ivan.utils;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * json和java对象的转换工具类，依赖于jackson
 * 
 * @author Thomason
 * @version 1.0
 */
public class JsonUtil {
	public static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	public static String obj2Json(Object obj, boolean ignoreNull) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			// 忽略空值输出
			if (ignoreNull) {
				mapper.getSerializationConfig().setSerializationInclusion(
						Inclusion.NON_NULL);
			}
			mapper.getSerializationConfig().setDateFormat(sdf);
			return mapper.writeValueAsString(obj);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static <X> X json2Obj(String jsonStr, Class<X> x) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(jsonStr, x);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
